package com.slh.touchandroid.fragment;

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.slh.touchandroid.R;
import com.slh.touchandroid.utils.Logging;
import com.slh.touchandroid.utils.Utils;

public class MirrorFragment extends BaseFragment {
	// ===============================================================
	private Camera mCamera;

	// ===============================================================
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setRetainInstance(true);
		mCamera = Utils.CameraHardware.getFrontCamera();
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			 ViewGroup container,  Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_mirror, container,
				false);
		if (mCamera != null) {
			((FrameLayout) rootView
					.findViewWithTag(getString(R.string.tag_camera_view)))
					.addView(new CameraPreview(getActivity(), mCamera));
		}
		return rootView;
	}

	@Override
	public void onDestroy() {
		Utils.CameraHardware.releaseCamera(mCamera);
		super.onDestroy();
	}

	// ===============================================================
	private static class CameraPreview extends SurfaceView implements
			SurfaceHolder.Callback {
		private SurfaceHolder mHolder;
		private Camera mCamera;

		public CameraPreview(Context context, Camera camera) {
			super(context);
			mCamera = camera;
			mHolder = getHolder();
			mHolder.addCallback(this);
			mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}

		public void surfaceCreated(SurfaceHolder holder) {
			try {
				mCamera.setPreviewDisplay(holder);
				mCamera.setDisplayOrientation(90);
				mCamera.startPreview();
			} catch (IOException e) {
			}
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int w,
				int h) {
			if (mHolder.getSurface() == null) {
				return;
			}
			try {
				mCamera.stopPreview();
			} catch (Exception e) {
				Logging.log(e);
			}
			try {
				mCamera.setPreviewDisplay(mHolder);
				mCamera.startPreview();

			} catch (Exception e) {
			}
		}
	}
	// ===============================================================
}
